<?php

namespace Sharks\Core\Http\Routing;

use Exception;
use Sharks\Core\Support\Base\Argument;
use Sharks\Core\Support\Base\Precondition;
use Sharks\Core\Support\Base\Str;

/**
 * 中间件文件读取
 */
class MiddlewaresConfReader {

    public static function read($filePath) {
        $middlewareCollection = new MiddlewareCollection();

        if (file_exists($filePath)) {

            $file = fopen($filePath, "r");
            $num = 1;
            while(!feof($file)){
                $line = fgets($file);
                try {

                    list($name, $class, $desc) = self::resolveLine($line, ++$num);
                    if (!empty($name)) {
                        $middlewareCollection->register($name, $class, $desc);
                    }
                }
                catch (Exception $e) {
                    $msg = $e->getMessage();
                    throw new \InvalidArgumentException("middlewares.conf $msg #line:$num");
                }
            }
            fclose($file);
        }
        return $middlewareCollection;
    }

    public static function resolveLine($line, $num = 1) {
        if (empty($line) || Str::isBlank($line)) {
            return;
        }
        // 按行读取
        $line = trim($line);
        if (Str::startsWith($line, '#')) {//如果以'#'开头,则为注释
            return;
        }
        else {
            $vars = preg_split('/\s+/', $line);
            Precondition::check(count($vars) > 1 && count($vars) < 4, "route.conf 文件格式不对 参数数目不正确 #line:$num");

            $name = $vars[0];
            $class = $vars[1];
            $desc = (count($vars) == 3) ? $vars[2] : null;

            return array($name, $class, $desc);
        }
    }
}